package service

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"LogisticsPort/utils"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"time"
)

func User(r *gin.Engine) {
	user := r.Group("/user")
	{
		user.POST(sql.RequestUpdate, UserUpdate)
		user.GET(sql.RequestData, UserGet)
		user.GET(sql.RequestDelete, UserDelete)
		user.GET(sql.RequestList, UserList)
		user.POST("/register", UserAdd)
		user.POST("/login", UserLogin)
		user.POST("/modify/password", ModifyPassword)
		user.GET("/searchHistory/modify", ModifySearchHistory)
		user.GET("/searchHistory/data", UserSearchHistory)
	}
}

func UserLogin(c *gin.Context) {
	sql.HttpHandle("登录", c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var user model.User
		phone := c.PostForm("phone")
		username := c.PostForm("username")
		password := c.PostForm("password")
		deviceId := c.PostForm("deviceId")
		if phone != "" {
			db.Where("phone = ?", phone).First(&user)
		} else if username != "" {
			db.Where("username = ?", username).First(&user)
		} else {
			db.Error = errors.New("账户错误")
			return db, nil
		}
		if password == "" || user.Password != password {
			db.Error = errors.New("密码错误")
			return db, nil
		}
		if deviceId == "" || (user.DeviceId != "" && user.DeviceId != deviceId) {
			db.Error = errors.New("账户已绑定其他手机设备")
			return db, nil
		}
		db.Model(&user).Update("device_id", deviceId)
		return db, user
	})
}

func UserAdd(c *gin.Context) {
	sql.HttpAdd(c, &model.User{}, nil)
}

func UserUpdate(c *gin.Context) {
	sql.HttpUpdates(c, &model.User{}, nil)
}

func UserDelete(c *gin.Context) {
	sql.HttpDeleteById(c, &model.User{})
}

func UserGet(c *gin.Context) {
	sql.HttpDataById(c, &model.User{})
}

func UserList(c *gin.Context) {
	sql.DBHandle(c, sql.GET, func(context *gin.Context, db *gorm.DB) interface{} {
		var list []model.User
		salesArea := c.Query("sales_area")
		numberPlate := c.Query("number_plate")
		logisticsCompany := c.Query("logistics_company")
		driverPhone := c.Query("driver_phone")
		parkingLocation := c.Query("parking_location")
		index := c.Query("pageIndex")
		size := c.Query("pageSize")
		pageIndex, indexErr := strconv.Atoi(index)
		pageSize, sizeError := strconv.Atoi(size)
		if salesArea != "" {
			db = db.Where("sales_area = ?", salesArea)
		}
		if numberPlate != "" {
			db = db.Where("number_plate = ?", numberPlate)
		}
		if logisticsCompany != "" {
			db = db.Where("logistics_company = ?", logisticsCompany)
		}
		if driverPhone != "" {
			db.Where("driver_phone = ?", driverPhone)
		}
		if parkingLocation != "" {
			db.Where("parking_location = ?", parkingLocation)
		}
		if indexErr == nil && sizeError == nil {
			db = db.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
		}
		db.Find(&list)
		return list
	})
}

func ModifyPassword(c *gin.Context) {
	sql.DBHandle(c, sql.UPDATE, func(context *gin.Context, db *gorm.DB) interface{} {
		user := new(model.User)
		oldPassword := c.Query("oldPassword")
		newPassword := c.Query("newPassword")
		accountId := c.Query("accountId")
		db.Where("id = ?", accountId).First(user)
		if oldPassword != user.Password {
			c.JSON(http.StatusOK, model.BaseJsonBean{Code: 200, Message: "原始密码错误"})
			return nil
		}
		db.Model(&user).Update("password", newPassword)
		if db.RowsAffected > 0 {
			return user
		}
		c.JSON(http.StatusOK, &model.BaseJsonBean{
			Code: 200, Message: "修改失败",
		})
		return nil
	})
}

func ModifySearchHistory(c *gin.Context) {
	sql.HttpHandle(sql.UPDATE, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		id := c.Query("id")
		searchStr := c.Query("searchStr")
		var user model.User
		db.Where("id = ?", id).First(&user)
		var str string
		var list []string
		if user.SearchHistory != "" {
			if err := json.Unmarshal([]byte(user.SearchHistory), &list); err != nil {
				db.Error = err
				return db, nil
			}
			for _, s := range list {
				if s == searchStr {
					list = utils.Remove(list, s)
				}
			}
		}
		list = append(list, searchStr)
		bytes, _ := json.Marshal(list)
		str = string(bytes)
		fmt.Println(time.DateTime)
		currentTime := time.Now().Format("2006-01-02 15:04:05")
		db.Model(&model.User{}).
			Where("id = ?", id).
			Updates(model.User{SearchHistory: str, SearchTime: currentTime})
		return db, list
	})
}

func UserSearchHistory(c *gin.Context) {
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		id := c.Query("id")
		var user model.User
		db.Where("id = ?", id).First(&user)
		if user.SearchHistory != "" {
			var list []string
			if err := json.Unmarshal([]byte(user.SearchHistory), &list); err != nil {
				db.Error = err
				return db, nil
			}
			return db, list
		}
		return db, nil
	})
}
